#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/2/11 21:40
# @Author  : 唐松
# @File    : conftest.py
# @Software: PyCharm
import time
from datetime import timedelta

from util_tools.notify.send_mail import SendEmail


def format_duration(seconds):
    """将秒数转换为时分秒格式"""
    return str(timedelta(seconds=seconds)).split('.')[0]


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    Pytest框架里面预定义的钩子函数，用于在测试结束后自动化收集测试结果
    :param terminalreporter:
    :param exitstatus:
    :param config:
    :return:
    """
    testcase_total = terminalreporter._numcollected
    passed_num = len(terminalreporter.stats.get('passed', []))
    failed_num = len(terminalreporter.stats.get('failed', []))
    error_num = len(terminalreporter.stats.get('error', []))
    skip_num = len(terminalreporter.stats.get('skipped', []))
    duration = round(time.time() - terminalreporter._sessionstarttime, 2)
    formatted_duration = format_duration(duration)

    # 统计通过率、失败率、错误率
    pass_rate = f"{(passed_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"
    fail_rate = f"{(failed_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"
    error_rate = f"{(error_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"

    summary = f"""
    自动化测试结果，通知如下，具体执行结果：
    测试用例总数：{testcase_total}  
    测试用例通过数：{passed_num}
    通过率：{pass_rate}
    测试用例失败数：{failed_num}
    失败率：{fail_rate}
    错误数量：{error_num}
    错误率：{error_rate}       
    跳过执行数量：{skip_num}
    执行总时长：{duration}s ({formatted_duration})
    """
    print(summary)

    SendEmail().send_email('接口测试框架结果', summary)
